package com.tenglong.teacher.ui.downApk.iUtil;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;

import com.tenglong.teacher.R;
import com.tenglong.teacher.ui.downApk.IContract;

import java.util.List;
import java.util.Locale;

/**
 * @author hdx on 2019/2/26.
 */
public class NotifyPresenterImpl implements IContract.INotify {
    private Context mContext;
    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder mBuilder;
    private static final int NOTIFY_ID = 1005;
    private Notification.Builder mBuilder8;

    public NotifyPresenterImpl(Context context) {
        this.mContext = context;
        init();
    }

    private void init() {
        if (mNotificationManager == null) {
            mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel("my_channel_01", "我是渠道名字", NotificationManager.IMPORTANCE_LOW);
                mNotificationManager.createNotificationChannel(mChannel);
                mBuilder8 = new Notification.Builder(mContext)
                        .setChannelId("my_channel_01")
                        .setContentTitle("正在连接服务器")
                        .setContentText("开始下载")
                        .setOngoing(true)
                        .setAutoCancel(true)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setWhen(System.currentTimeMillis());
            } else {
                mBuilder = new NotificationCompat.Builder(mContext);
                mBuilder.setContentTitle("开始下载")
                        .setContentText("正在连接服务器")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setOngoing(true)
                        .setAutoCancel(true)
                        .setWhen(System.currentTimeMillis());
            }
        }
    }

    @Override
    public void prepare() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.notify(NOTIFY_ID, mBuilder8.build());
        } else {
            mNotificationManager.notify(NOTIFY_ID, mBuilder.build());
        }
    }

    @Override
    public void progress(String title, int progress) {
        Notification notification;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = mBuilder8.setContentTitle(title)
                    .setContentText(String.format(Locale.CHINESE, "%d%%", progress))
                    .setProgress(100, progress, false)
                    .setWhen(System.currentTimeMillis()).build();
        } else {
            notification = mBuilder.setContentTitle(title)
                    .setContentText(String.format(Locale.CHINESE, "%d%%", progress))
                    .setProgress(100, progress, false)
                    .setWhen(System.currentTimeMillis()).build();
        }
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(NOTIFY_ID, notification);
    }

    @Override
    public void complete(String title, String msg, Intent intent) {
        if (intent == null) return;
        if (onFront()) {
            cancel();
            mContext.startActivity(intent);
//            //弹出安装窗口把原程序关闭。
//            //避免安装完毕点击打开时没反应
//            killProcess(android.os.Process.myPid());
        } else {
            PendingIntent pIntent = PendingIntent.getActivity(mContext.getApplicationContext()
                    , 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Notification notification;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notification = mBuilder8.setContentIntent(pIntent)
                        .setContentTitle(title)
                        .setContentText(msg)
                        .setProgress(0, 0, false)
                        .setDefaults(Notification.DEFAULT_ALL).build();
                mNotificationManager.notify(NOTIFY_ID, mBuilder8.build());
            } else {
                notification = mBuilder.setContentIntent(pIntent)
                        .setContentTitle(title)
                        .setContentText(msg)
                        .setProgress(0, 0, false)
                        .setDefaults(Notification.DEFAULT_ALL).build();
            }
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(NOTIFY_ID, notification);
        }
    }

    @Override
    public void clear() {
        if (mNotificationManager != null) {
            mNotificationManager.cancelAll();
            mNotificationManager = null;
        }
        if (mBuilder != null) {
            mBuilder = null;
        }
        if (mBuilder8 != null) {
            mBuilder8 = null;
        }
    }

    @Override
    public void cancel() {
        mNotificationManager.cancel(NOTIFY_ID);
    }

    @Override
    public void fail(String title, String msg) {
        Notification notification;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = mBuilder8.setContentTitle(title)
                    .setContentText(msg).build();
        } else {
            notification = mBuilder.setContentTitle(title)
                    .setContentText(msg).build();
        }
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(NOTIFY_ID, notification);
    }

    private boolean onFront() {
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null || appProcesses.isEmpty())
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(mContext.getPackageName()) &&
                    appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }
}
